<?php
require('includes/top.php');

foreach($_FILES as $key => $value)
{
if($value['error']=='0')
{

$id = explode('userfile_',$key);
$target_path = "images/reciept/Accessories/";
$target_path = $target_path . basename($_FILES[$key]['name']); 

$date = date("d-m-y");
$user_name=$_SESSION['user_name'];

if(move_uploaded_file($_FILES[$key]['tmp_name'], $target_path)) {


$sql="INSERT INTO dispatched_accessories(`accessories_id`,`receipt`,`user_id`,`date`,`user_name`) VALUES ('".trim($id[1])."','".basename( $_FILES[$key]['name'])."','".trim($id[2])."','$date','$user_name')";
$result=mysql_query($sql);
$sql2="UPDATE accessories SET `received` = '1' , `dispatch` = '1' WHERE accessories_id = '".trim($id[1])."' and user_id = '".trim($id[2])."'";
$result2=mysql_query($sql2);
header('Location:dispatch_accessories.php?v=success');
} else{
header('Location:dispatch_accessories.php?v=err');
}
}
else
{
header('Location:dispatch_accessories.php?v=imerr');
}
}

foreach($_POST as $key => $value)
{
$id = explode('received_',$key);

if($id[1]!="") {
$date = date("d-m-y");
$query = mysql_query("Select recived from accessories where accessories_id = '".trim($id[1])."' and user_id = '".trim($id[2])."'");
$result_query = mysql_fetch_array($query);
	if($result_query[0]=='0');
	{
		$sql3="INSERT INTO received_accessories(`accessories_id`,`date`,`user_name`,`user_id`) VALUES ('".trim($id[1])."','$date','".$_SESSION['user_name']."','".trim($id[2])."')";
		
		$query = mysql_query("SELECT accessories_name,dispatch_location FROM accessories where accessories_id = '".trim($id[1])."' and user_id = '".trim($id[2])."'");
$queryresult = mysql_fetch_array($query);

$locquery = mysql_query("SELECT user_email_address FROM users where user_id = '".trim($id[2])."'");
$locqueryresult = mysql_fetch_array($locquery);


// recipients
$to  = $locqueryresult['user_email_address'];
// subject
$subject = 'Login Details';

// message
$message = '
<html>
<head>
  <title>Laptrak</title>
</head>
<body>
  <p><strong>Following Accessories needs to be delivered:</strong></p>
  <table>
    <tr>
      <td>Accessories :</td><td>'.$queryresult['accessories_name'].'</td>
    </tr>    
  </table>
</body>
</html>
';

// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To:' . $to . "\r\n";
	$headers .= 'From: no-reply@laptrak.com' . "\r\n";

	// Mail it
	mail($to, $subject, $message, $headers);

		$result3=mysql_query($sql3);

		$sql1="UPDATE accessories SET `received` = '1' WHERE accessories_id = '".trim($id[1])."' and user_id = '".trim($id[2])."'";
		$result1=mysql_query($sql1);
	}
}
}
header('Location:dispatch_accessories.php?v=success');
?>